package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.ThreadLocalUtil;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.dto.business.BusinessFollowDTO;
import com.qk.dto.business.PoolDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.QueryBusinessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    @Override
    public PageResult<Business> pool(PoolDTO dto) {
        Page<Business> page = new Page<>(dto.getPage(), dto.getPageSize());
        Page<Business> businessPageResult = baseMapper.selectPage(page, Wrappers.lambdaQuery(Business.class).
                eq(dto.getBusinessId() != null, Business::getId, dto.getBusinessId())
                .like(StringUtils.isNotBlank(dto.getName()), Business::getName, dto.getName())
                .like(StringUtils.isNotBlank(dto.getPhone()), Business::getPhone, dto.getPhone())
                .eq(dto.getSubject() != null, Business::getSubject, dto.getSubject())
                .eq(Business::getStatus, BusinessStatusConstants.RECOVERY));
        return PageResult.<Business>builder().total((int) businessPageResult.getTotal()).rows(businessPageResult.getRecords()).build();
    }
    @Override
    public void followBusiness(BusinessFollowDTO dto) {
        Business business = BeanUtil.copyProperties(dto, Business.class);
        if (business.getStatus() == BusinessStatusConstants.WAIT_FOLLOW_UP) {
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }
        business.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(business);
        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecord.setId(null);
        businessTrackRecord.setBusinessId(business.getId());
        businessTrackRecord.setUserId(ThreadLocalUtil.getClueContext());
        businessTrackRecordMapper.insert(businessTrackRecord);
    }
    @Override
    public QueryBusinessVO queryById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        Integer userId = business.getUserId();
        User user = userMapper.selectById(userId);
        List<BusinessTrackRecord> businessTrackRecords = businessTrackRecordMapper.selectList(Wrappers.<BusinessTrackRecord>lambdaQuery().in(BusinessTrackRecord::getBusinessId, id));
        QueryBusinessVO queryBusinessVO = BeanUtil.copyProperties(business, QueryBusinessVO.class);
        List<QueryBusinessVO.TrackRecordVO> list = businessTrackRecords.stream().map(item -> {
            QueryBusinessVO.TrackRecordVO vo = BeanUtil.copyProperties(item, QueryBusinessVO.TrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        queryBusinessVO.setTrackRecords(list);
        return queryBusinessVO;
    }
    @Override
    public void businessToCustomer(Integer id) {
        if (ObjectUtil.isEmpty(id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = this.getById(id);
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.CONVERT_TO_CUSTOMER);
        this.updateById(business);
        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setId(null);
        customer.setBusinessId(business.getId());
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customerMapper.insert(customer);
    }
    @Override
    public void backBusiness(Integer id) {
        if (ObjectUtil.isEmpty(id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = this.getById(id);
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.RECOVERY);
        this.updateById(business);
    }
    @Override
    public void addBusiness(BusinessDTO dto) {
        if (ObjectUtil.isEmpty(dto.getPhone())||ObjectUtil.isEmpty(dto.getName())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        this.save(business);
    }
    @Override
    public PageResult<BusinessDO> businessList(BusinessListDTO dto) {
        Page pages = new Page<>(dto.getPage(), dto.getPageSize());
        Page<BusinessDO> businessDOPage = this.baseMapper.selectByPageMp(pages,dto);
        return PageResult.<BusinessDO>builder()
                .total(Long.valueOf(businessDOPage.getTotal()).intValue())
                .rows(businessDOPage.getRecords())
                .build();

    }
}
